package com.numberma.userservice.Utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * IP地址工具类
 */
public class IpUtils {

    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST_IP = "127.0.0.1";
    private static final String LOCALHOST_IPV6 = "0:0:0:0:0:0:0:1";
    private static final String SEPARATOR = ",";

    /**
     * 获取客户端IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return UNKNOWN;
        }

        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (LOCALHOST_IP.equals(ip) || LOCALHOST_IPV6.equals(ip)) {
                // 根据网卡取本机配置的IP
                try {
                    ip = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException e) {
                    // ignore
                }
            }
        }

        // 对于通过多个代理的情况，第一个IP为客户端真实IP
        if (StringUtils.isNotEmpty(ip) && ip.contains(SEPARATOR)) {
            ip = ip.split(SEPARATOR)[0];
        }

        return StringUtils.isBlank(ip) ? UNKNOWN : ip.trim();
    }

    /**
     * 检查是否为内部IP地址
     */
    public static boolean isInternalIp(String ip) {
        if (StringUtils.isBlank(ip)) {
            return false;
        }

        byte[] addr = textToNumericFormatV4(ip);
        return isInternalIp(addr);
    }

    private static boolean isInternalIp(byte[] addr) {
        if (addr == null || addr.length < 2) {
            return false;
        }

        final byte b0 = addr[0];
        final byte b1 = addr[1];

        // 10.x.x.x/8
        if (b0 == 10) {
            return true;
        }
        // 172.16.x.x/12
        if (b0 == -84 && b1 >= 16 && b1 <= 31) {
            return true;
        }
        // 192.168.x.x/16
        if (b0 == -64 && b1 == -88) {
            return true;
        }
        // 127.0.0.0/8
        if (b0 == 127) {
            return true;
        }

        return false;
    }

    /**
     * 将IPv4地址转换成字节
     */
    private static byte[] textToNumericFormatV4(String text) {
        if (StringUtils.isBlank(text)) {
            return null;
        }

        String[] parts = text.split("\\.");
        if (parts.length != 4) {
            return null;
        }

        byte[] bytes = new byte[4];
        try {
            for (int i = 0; i < parts.length; i++) {
                int octet = Integer.parseInt(parts[i]);
                if (octet < 0 || octet > 255) {
                    return null;
                }
                bytes[i] = (byte) octet;
            }
        } catch (NumberFormatException e) {
            return null;
        }

        return bytes;
    }

    /**
     * 获取当前请求的IP地址（简化版）
     */
    public static String getCurrentIp() {
        HttpServletRequest request = getRequest();
        return request != null ? getIpAddr(request) : LOCALHOST_IP;
    }

    /**
     * 获取当前HttpServletRequest对象
     */
    private static HttpServletRequest getRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        } catch (Exception e) {
            return null;
        }
    }
}